/** SimpleServerO3.java
 *     This server serves multiple connections.
 *     */


import java.io.*;
import java.net.*;

public class SimpleServer03 {

    public static void main(String arg[]){
	ServerSocket		ssk = null;
	Socket			sk = null;
	int			cnCount = 0;
	Thread			agent = null;

	try {
	    System.out.printf("SimpleServer03 can serve mulpile client connections\n");
	    ssk = new ServerSocket(9903);

	    while ( true ) {
	        System.out.printf("\n\t\tCnnections made : %d\n", cnCount);
	        System.out.printf("\n\t\tWaiting for more connections ... ");
	        sk = ssk.accept();
	        agent = new Thread ( new Agent( ++ cnCount, sk ) );
		agent.start();
	   }
	} catch( IOException e) { e.printStackTrace();  } 
    }
}

class Agent implements Runnable {

   InputStream		reader= null;
   OutputStream		writer = null;
   Socket		socket = null;
   int			ID;
   public Agent( int id, Socket sk ) {
      ID = id; socket = sk;
      try {
         reader = sk.getInputStream() ;
         writer = sk.getOutputStream() ;
      } catch (IOException e) {}
   }


   public void run() {

	byte			buf[] = new byte[200];
	String			msg = null;
	int			msgCount = 0, k;

     try {
	while ( true ) {
	  k = reader.read(buf); 
	  if ( k > 0 ) 
	      System.out.printf("SERVER Agent %d: %s\n", ID, new String(buf) );
	  msg = "SERVER MESSAGE " + (++ msgCount) + " from agent " + ID;
	  writer.write(msg.getBytes());
	  writer.flush();

	}
     } catch ( Exception e) { } 
   }
}
